#include "Debug.h"

#include <cstdio>
#include <cstdlib>

#include <fcntl.h>
#include <unistd.h>

namespace dwarf {

Debug::Debug(bool &_rtn, const char *_file)
		: data_(NULL),
		  fd_(open(_file, O_RDONLY)) {
	if (fd_ < 0) {
		fprintf(stderr, "[ERR] (%s, %d) %s\n", __FILE__, __LINE__, __FUNCTION__);
		_rtn = false;
		return;
	}
	Dwarf_Error error;
	if (dwarf_init(fd_, DW_DLC_READ, NULL, NULL, &data_, &error) != DW_DLV_OK) {
		fprintf(stderr, "[ERR] (%s, %d) %s\n", __FILE__, __LINE__, __FUNCTION__);
		_rtn = false;
		return;
	}
	_rtn = true;
}

Debug::Debug(const Debug &_debug)
		: data_(_debug.data_),
		  fd_(_debug.fd_) {
	((Debug *) &_debug)->data_ = NULL;
	((Debug *) &_debug)->fd_ = -1;
}

Debug::~Debug() {
	if (data_ != NULL) {
		Dwarf_Error error;
		if (dwarf_finish(data_, &error) != DW_DLV_OK) {
			fprintf(stderr, "[ERR] (%s, %d) %s\n", __FILE__, __LINE__, __FUNCTION__);
			exit(-1);
		}
	}
	if (fd_ >= 0) {
		close(fd_);
	}
}

Dwarf_Debug Debug::getData() const {
	return data_;
}

}
